package com.unitd.frame.comm.utils.template;

import com.unitd.frame.comm.utils.ExceptionUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

 /**
 * @desc FreeMarkers工具类
 * @filename FreeMarkerUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/27
 */
public class FreeMarkerUtils {

	public static String renderString(String templateString, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template t = new Template("name", new StringReader(templateString), new Configuration());
			t.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		}
	}

	public static String renderTemplate(Template template, Object model) {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		}
	}

	public static Configuration buildConfiguration(String directory) throws IOException {
		Configuration cfg = new Configuration();
		Resource path = new DefaultResourceLoader().getResource(directory);
		cfg.setDirectoryForTemplateLoading(path.getFile());
		return cfg;
	}

	public static void main(String[] args) throws IOException {
//		// renderString
		Map<String, String> model = com.google.common.collect.Maps.newHashMap();
		model.put("userName", "calvin");
		String result = renderString("hello ${userName}", model);
		System.out.println(result);
		// renderTemplate
		Configuration cfg = buildConfiguration("classpath:/");
		Template template = cfg.getTemplate("testTemplate.ftl");
		String result2 = renderTemplate(template, model);
		System.out.println(result2);

		Map<String, String> model2 = com.google.common.collect.Maps.newHashMap();
		model2.put("userName", "calvin");
		String result3 = renderString("hello ${userName} ${r'${userName}'}", model2);
		System.out.println(result3);
	}
}